#!/bin/sh

if [ "X$ARCH" == "X" ]; then
    BUILD_ARCH=aarch64 # or arm for arm32
    #BUILD_ARCH=arm # or aarch64 for arm64
else
	BUILD_ARCH=$ARCH
fi

if [ "X$LIST" == "X" ]; then
    BUILD_LIST="bash strace gdb vim coreutils util-linux curl valgrind openssl"
else
    BUILD_LIST=$LIST
fi
BUILD_RELEASE=true

if [ "X$1" == "Xshell" ] ; then
    SHELLCMD=""
else
    SHELLCMD="-c /opt/tools/scripts/build_packages.sh"
fi

case $BUILD_ARCH in
    arm)
        TOOLCHAIN_TARGET=arm-linux-musleabi
        ;;
    aarch64)
        TOOLCHAIN_TARGET=aarch64-linux-musleabi
        ;;
    *)
        echo "UNKNOWN ARCH " $BUILD_ARCH
        exit
        ;;
esac
TOOLCHAIN_PREFIX=${TOOLCHAIN_TARGET}-
DEBUGROOT=/data/debugroot

BUILD_CFG="--env TOOLCHAIN_TARGET=${TOOLCHAIN_TARGET} "
BUILD_CFG+="--env BUILD_ARCH=${BUILD_ARCH} "
BUILD_CFG+="--env DEBUGROOT=${DEBUGROOT} "
BUILD_CFG+="--env TOOLCHAIN_PREFIX=${TOOLCHAIN_TARGET}- "
BUILD_CFG+="--env CC=${TOOLCHAIN_PREFIX}gcc "
BUILD_CFG+="--env STRIP=${TOOLCHAIN_PREFIX}strip "
#DOCKER_LIBRARY_PATH=${DEBUGROOT}/lib
BUILD_CFG+="--env LDFLAGS=-L${DEBUGROOT}/lib "
BUILD_CFG+="--env PKG_CONFIG_PATH=${DEBUGROOT}/pkgconfig "

SCRIPTS_DIR=$(cd $(dirname "$0"); pwd)
ROOT_DIR=$(cd ${SCRIPTS_DIR}/..; pwd)
BUILD_DIR=${ROOT_DIR}/build
OUT_DIR=${ROOT_DIR}/out
CCACHE_DIR=${ROOT_DIR}/CCACHE_TMP

mkdir -p ${BUILD_DIR} ${OUT_DIR}

echo "mounting ...."
echo ${OUT_DIR}:/data
echo ${BUILD_DIR}:/opt/build
echo ${CCACHE_DIR}:/CCACHE
echo ${SCRIPTS_DIR}:/opt/tools/scripts

#PROXYCFG=""

[ "X$http_proxy" == "X" ] || PROXYCFG+="--env http_proxy=${http_proxy} "
[ "X$https_proxy" == "X" ] || PROXYCFG+="--env https_proxy=${https_proxy} "
[ "X$ftp_proxy" == "X" ] || PROXYCFG+="--env ftp_proxy=${ftp_proxy} "
[ "X$no_proxy" == "X" ] || PROXYCFG+="--env no_proxy=${ftp_proxy} "

set -x
docker run -it --rm --network host \
	-v ${OUT_DIR}:/data \
	-v ${BUILD_DIR}:/opt/build \
	-v ${CCACHE_DIR}:/CCACHE \
	-v ${SCRIPTS_DIR}:/opt/tools/scripts \
	--env BUILD_LIST="${BUILD_LIST}" \
	--env BUILD_RELEASE=${BUILD_RELEASE} \
	--env BUILD_DIR=/opt/build \
	--env SCRIPTS_DIR="/opt/tools/scripts" \
    ${BUILD_CFG} \
	${PROXYCFG} \
	ohos_musl_tools_builder \
    /bin/bash $SHELLCMD

